using Microsoft.EntityFrameworkCore;
using Universal.Application.Contracts.Common;
using Universal.Application.Contracts.Dto.Article;
using Universal.Application.Repositories;
using Universal.Domain.Entities.App;
using Universal.Domain.Enums;
using Universal.Domain.Repositories;

namespace Universal.Application.Services;

/// <summary>
/// 文章服务
/// </summary>
public class ArticleService : IArticleService
{
    private readonly IRepository<AppArticle> _articleRepository;
    private readonly IRepository<AppArticleCategory> _categoryRepository;
    private readonly IRepository<AppUser> _userRepository;

    public ArticleService(
        IRepository<AppArticle> articleRepository,
        IRepository<AppArticleCategory> categoryRepository,
        IRepository<AppUser> userRepository)
    {
        _articleRepository = articleRepository;
        _categoryRepository = categoryRepository;
        _userRepository = userRepository;
    }

    /// <summary>
    /// 获取文章分页列表
    /// </summary>
    public async Task<ApiResponse<PagedResult<ArticleDto>>> GetArticlesPagedAsync(int pageIndex, int pageSize)
    {
        var (articles, totalCount) = await _articleRepository.GetPagedAsync(pageIndex, pageSize, 
            a => a.Category!, a => a.User!); // 修复：使用 null-forgiving operator

        var articleDtos = articles.Select(a => new ArticleDto
        {
            Id = a.Id,
            Title = a.Title,
            Content = a.Content,
            Summary = a.Summary,
            Status = a.Status,
            Tags = a.Tags,
            CategoryId = a.CategoryId,
            CategoryName = a.Category?.ArticleCategoryName ?? string.Empty,
            UserId = a.UserId,
            UserName = a.User?.Username ?? string.Empty,
            CreatedAt = a.CreatedAt,
            UpdatedAt = a.UpdatedAt
        }).ToList();

        var pagedResult = new PagedResult<ArticleDto>
        {
            TotalCount = totalCount,
            TotalPages = (int)Math.Ceiling(totalCount / (double)pageSize),
            PageIndex = pageIndex,
            PageSize = pageSize,
            Items = articleDtos
        };

        return ApiResponse<PagedResult<ArticleDto>>.Success(pagedResult);
    }

    /// <summary>
    /// 根据条件查询文章
    /// </summary>
    public async Task<ApiResponse<PagedResult<ArticleDto>>> QueryArticlesAsync(ArticleQueryDto query)
    {
        var baseQuery = _articleRepository.Query();

        // 条件拼接
        if (!string.IsNullOrWhiteSpace(query.Title))
        {
            baseQuery = baseQuery.Where(a => a.Title.Contains(query.Title));
        }
        if (!string.IsNullOrWhiteSpace(query.Tags))
        {
            baseQuery = baseQuery.Where(a => a.Tags != null && a.Tags.Contains(query.Tags));
        }
        // 修复：检查可空Guid
        if (query.CategoryId.HasValue && query.CategoryId.Value != Guid.Empty)
        {
            baseQuery = baseQuery.Where(a => a.CategoryId == query.CategoryId);
        }
        if (query.Status.HasValue)
        {
            baseQuery = baseQuery.Where(a => (int)a.Status == query.Status);
        }

        // 包含导航属性
        var queryable = baseQuery.Include(a => a.Category!).Include(a => a.User!); // 修复：使用 null-forgiving operator

        var totalCount = await queryable.CountAsync();

        var articles = await queryable
            .OrderByDescending(a => a.CreatedAt)
            .Skip((query.PageIndex - 1) * query.PageSize)
            .Take(query.PageSize)
            .ToListAsync();

        var articleDtos = articles.Select(a => new ArticleDto
        {
            Id = a.Id,
            Title = a.Title,
            Content = a.Content,
            Summary = a.Summary,
            Status = a.Status,
            Tags = a.Tags,
            CategoryId = a.CategoryId,
            CategoryName = a.Category?.ArticleCategoryName ?? string.Empty,
            UserId = a.UserId,
            UserName = a.User?.Username ?? string.Empty,
            CreatedAt = a.CreatedAt,
            UpdatedAt = a.UpdatedAt
        }).ToList();

        var pagedResult = new PagedResult<ArticleDto>
        {
            Items = articleDtos,
            TotalCount = totalCount,
            TotalPages = (int)Math.Ceiling(totalCount / (double)query.PageSize),
            PageIndex = query.PageIndex,
            PageSize = query.PageSize
        };

        return ApiResponse<PagedResult<ArticleDto>>.Success(pagedResult);
    }

    /// <summary>
    /// 获取单个文章详情
    /// </summary>
    public async Task<ApiResponse<ArticleDto?>> GetArticleByIdAsync(Guid id)
    {
        var article = await _articleRepository.GetByIdWithIncludesAsync(id, a => a.Category!, a => a.User!);
        
        if (article == null)
            return ApiResponse<ArticleDto?>.Failure(404, "文章不存在");

        var articleDto = new ArticleDto
        {
            Id = article.Id,
            Title = article.Title,
            Content = article.Content,
            Summary = article.Summary,
            Status = article.Status,
            Tags = article.Tags,
            CategoryId = article.CategoryId,
            CategoryName = article.Category?.ArticleCategoryName ?? string.Empty,
            UserId = article.UserId,
            UserName = article.User?.Username ?? string.Empty,
            CreatedAt = article.CreatedAt,
            UpdatedAt = article.UpdatedAt
        };

        return ApiResponse<ArticleDto?>.Success(articleDto);
    }

    /// <summary>
    /// 创建文章
    /// </summary>
    public async Task<ApiResponse<ArticleDto>> CreateArticleAsync(CreateArticleDto dto, Guid userId)
    {
        // 参数校验
        if (dto == null)
        {
            System.Diagnostics.Debug.WriteLine("DTO 为 null");
            return ApiResponse<ArticleDto>.Failure(400, "参数不能为空");
        }
        
        if (string.IsNullOrWhiteSpace(dto.Title))
        {
            System.Diagnostics.Debug.WriteLine("标题为空");
            return ApiResponse<ArticleDto>.Failure(400, "文章标题不能为空");
        }
        
        if (string.IsNullOrWhiteSpace(dto.Content))
        {
            System.Diagnostics.Debug.WriteLine("内容为空");
            return ApiResponse<ArticleDto>.Failure(400, "文章内容不能为空");
        }
        
        // 调试日志 - 查看接收到的数据
        System.Diagnostics.Debug.WriteLine($"=== 创建文章调试信息 ===");
        System.Diagnostics.Debug.WriteLine($"Title: {dto.Title}");
        System.Diagnostics.Debug.WriteLine($"Content: {dto.Content}");
        System.Diagnostics.Debug.WriteLine($"CategoryIds: {dto.CategoryIds?.Count ?? 0}");
        if (dto.CategoryIds != null)
        {
            foreach (var id in dto.CategoryIds)
            {
                System.Diagnostics.Debug.WriteLine($"  CategoryId: {id}");
            }
        }
        System.Diagnostics.Debug.WriteLine($"CategoryId: {dto.CategoryId}");
        System.Diagnostics.Debug.WriteLine($"========================");
        
        // 检查分类ID - 支持多分类或单分类
        var categoryIds = new List<Guid>();
        if (dto.CategoryIds != null && dto.CategoryIds.Any())
        {
            categoryIds = dto.CategoryIds;
            System.Diagnostics.Debug.WriteLine($"使用 CategoryIds: {string.Join(", ", categoryIds)}");
        }
        else if (dto.CategoryId.HasValue && dto.CategoryId.Value != Guid.Empty)
        {
            categoryIds.Add(dto.CategoryId.Value);
            System.Diagnostics.Debug.WriteLine($"使用 CategoryId: {dto.CategoryId.Value}");
        }
        else
        {
            System.Diagnostics.Debug.WriteLine("没有找到有效的分类ID");
            return ApiResponse<ArticleDto>.Failure(400, "文章分类不能为空");
        }
        
        // 验证分类是否存在
        foreach (var categoryId in categoryIds)
        {
            var category = await _categoryRepository.GetByIdAsync(categoryId);
            if (category == null)
                return ApiResponse<ArticleDto>.Failure(400, $"指定的文章分类 {categoryId} 不存在");
        }
        
        // 验证用户是否存在
        var user = await _userRepository.GetByIdAsync(userId);
        if (user == null)
            return ApiResponse<ArticleDto>.Failure(400, "用户不存在");

        // 创建文章 - 暂时使用第一个分类作为主分类
        var article = new AppArticle
        {
            Title = dto.Title,
            Content = dto.Content,
            Summary = dto.Summary,
            Status = dto.Status,
            Tags = dto.Tags,
            CategoryId = categoryIds.First(), // 使用第一个分类作为主分类
            UserId = userId
        };

        var created = await _articleRepository.AddAsync(article);
        
        var result = new ArticleDto
        {
            Id = created.Id,
            Title = created.Title,
            Content = created.Content,
            Summary = created.Summary,
            Status = created.Status,
            Tags = created.Tags,
            CategoryId = created.CategoryId,
            CategoryName = created.Category?.ArticleCategoryName ?? string.Empty,
            UserId = created.UserId,
            UserName = created.User?.Username ?? string.Empty,
            CreatedAt = created.CreatedAt,
            UpdatedAt = created.UpdatedAt
        };

        return ApiResponse<ArticleDto>.Success(result, "文章创建成功");
    }

    /// <summary>
    /// 更新文章
    /// </summary>
    public async Task<ApiResponse<bool>> UpdateArticleAsync(UpdateArticleDto dto)
    {
        // 参数校验
        if (dto == null)
            return ApiResponse<bool>.Failure(400, "参数不能为空");
        
        if (dto.Id == Guid.Empty)
            return ApiResponse<bool>.Failure(400, "文章ID不能为空");
        
        if (string.IsNullOrWhiteSpace(dto.Title))
            return ApiResponse<bool>.Failure(400, "文章标题不能为空");
        
        if (string.IsNullOrWhiteSpace(dto.Content))
            return ApiResponse<bool>.Failure(400, "文章内容不能为空");
        
        // 检查分类ID - 支持多分类或单分类
        var categoryIds = new List<Guid>();
        if (dto.CategoryIds != null && dto.CategoryIds.Any())
        {
            categoryIds = dto.CategoryIds;
        }
        else if (dto.CategoryId.HasValue && dto.CategoryId.Value != Guid.Empty)
        {
            categoryIds.Add(dto.CategoryId.Value);
        }
        else
        {
            return ApiResponse<bool>.Failure(400, "文章分类不能为空");
        }

        var article = await _articleRepository.GetByIdAsync(dto.Id);
        if (article == null)
            return ApiResponse<bool>.Failure(404, "文章不存在");

        // 验证分类是否存在
        foreach (var categoryId in categoryIds)
        {
            var category = await _categoryRepository.GetByIdAsync(categoryId);
            if (category == null)
                return ApiResponse<bool>.Failure(400, $"指定的文章分类 {categoryId} 不存在");
        }

        article.Title = dto.Title;
        article.Content = dto.Content;
        article.Summary = dto.Summary;
        article.Status = dto.Status;
        article.Tags = dto.Tags;
        article.CategoryId = categoryIds.First(); // 使用第一个分类作为主分类
        article.UpdatedAt = DateTime.UtcNow;

        await _articleRepository.UpdateAsync(article);
        return ApiResponse<bool>.Success(true, "文章更新成功");
    }

    /// <summary>
    /// 删除文章
    /// </summary>
    public async Task<ApiResponse<bool>> DeleteArticleAsync(Guid id)
    {
        var article = await _articleRepository.GetByIdAsync(id);
        if (article == null)
            return ApiResponse<bool>.Failure(404, "文章不存在");

        await _articleRepository.DeleteAsync(article);
        return ApiResponse<bool>.Success(true, "文章删除成功");
    }

    /// <summary>
    /// 更新文章状态
    /// </summary>
    public async Task<ApiResponse<bool>> UpdateArticleStatusAsync(Guid id, int status)
    {
        var article = await _articleRepository.GetByIdAsync(id);
        if (article == null)
            return ApiResponse<bool>.Failure(404, "文章不存在");

        if (!Enum.IsDefined(typeof(ArticleStatus), status))
            return ApiResponse<bool>.Failure(400, "无效的文章状态");

        article.Status = (ArticleStatus)status;
        article.UpdatedAt = DateTime.UtcNow;

        await _articleRepository.UpdateAsync(article);
        return ApiResponse<bool>.Success(true, "文章状态更新成功");
    }
}